package logControllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/gomodule/redigo/redis"
	"lazyops_go/models"
	"lazyops_go/tools"
	"regexp"
)

type LogController struct {
	beego.Controller
}

func (c *LogController) IndexUserLog() {
	cur_page, _ := c.GetInt(":page", 1)
	cur_user := c.GetSession("cur_user")
	is_super := c.GetSession("is_super")
	count := models.QueryLogUserCount(is_super.(bool), cur_user.(string))
	data_list := models.PageLogUserAll(cur_page, is_super.(bool), cur_user.(string))
	page := tools.CreatePaging(cur_page, 12, count)
	cur_user_menus := c.GetSession("cur_user_menus")
	c.Data["page"] = page
	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["data_list"] = data_list
	c.Data["label"] = "用户日志"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "log/userlogjs.html"
	c.TplName = "log/userlog.html"
}

func (c *LogController) SearchUserLog() {
	key := c.Ctx.Input.Param(":key")
	cur_user := c.GetSession("cur_user")
	is_super := c.GetSession("is_super")
	data_list := models.QueryLogUserSearch(key, cur_user.(string), is_super.(bool))
	page := tools.CreatePaging(1, len(data_list), len(data_list))
	c.Data["page"] = page
	cur_user_menus := c.GetSession("cur_user_menus")
	c.Data["key"] = key
	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["data_list"] = data_list
	c.Data["label"] = "用户日志"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "log/userlogjs.html"
	c.TplName = "log/userlog.html"
}

func (c *LogController) IndexTaskLog() {
	cur_user := c.GetSession("cur_user")
	is_super := c.GetSession("is_super")
	cur_user_menus := c.GetSession("cur_user_menus")
	cur_page, _ := c.GetInt(":page", 1)
	task_list := models.QueryLogTaskAll(cur_user.(string), is_super.(bool))
	task_broker := beego.AppConfig.String("task_broker")
	rds, _ := redis.DialURL(task_broker)
	defer rds.Close()
	for _, v := range task_list {
		if v.Status == "PENDING" || v.TaskRet =="" {
			//通过redis 获取任务结果
			rds_key := fmt.Sprintf("celery-task-meta-%s", v.TaskId)
			ret, err := redis.String(rds.Do("get", rds_key))
			//redis 结果格式化，json转string
			m := map[string]interface{}{}
			json.Unmarshal([]byte(ret), &m);
			var rds_ret string
			for k, vv := range m {
				switch k {
				case "result":
					rds_ret = tools.TypeToString(vv)
				case "status":
					v.Status = vv.(string)
				}
			}
			v.TaskRet = rds_ret
			//获取字典中配置的错误关键字
			ditc_obj, err := models.QueryDictKey("ERRER_KEY")
			if err != nil {
				fmt.Println("ERRER_KEY未配置")
			}else {
				if v.TaskType {
					reg_error := regexp.MustCompile(`ERROR`)
					re_error := reg_error.FindAllString(rds_ret, -1)
					reg_warn := regexp.MustCompile(`WARNING`)
					re_warnr := reg_warn.FindAllString(rds_ret, -1)
					if len(re_error) > 0 {
						v.Status = "ERROR"
					} else if  len(re_warnr) > 0{
						v.Status = "WARNING"
					}else{
						if len(v.TaskRet)>0 {
							v.Status = "SUCCESS"
						}else{
							v.Status = "PENDING"
						}
					}
				}else {
					//匹配关键字，忽略大小写
					reg := regexp.MustCompile(`(?i:` + ditc_obj.DictVal + `)`)
					re_err := reg.FindAllString(rds_ret, -1)
					if len(re_err) > 0 {
						reg_error := regexp.MustCompile(`(?i:error)`)
						re_error := reg_error.FindAllString(rds_ret, -1)
						if len(re_error) > 0 {
							v.Status = "ERROR"
						} else {
							v.Status = "WARNING"
						}
					}
				}
				models.UpdateTask(v.ID, v)
			}
		}
	}

	count_list := models.QueryLogTaskAll(cur_user.(string), is_super.(bool))
	data_list := models.QueryLogTaskPage(cur_page, cur_user.(string), is_super.(bool))
	page := tools.CreatePaging(cur_page, 12, len(count_list))

	c.Data["page"] = page
	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["data_list"] = data_list
	c.Data["label"] = "任务日志"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "log/taskjs.html"
	c.TplName = "log/task.html"
}

func (c *LogController) SearchTaskLog() {
	cur_user := c.GetSession("cur_user")
	is_super := c.GetSession("is_super")
	key := c.Ctx.Input.Param(":key")
	data_list := models.QueryTaskSearch(key, cur_user.(string), is_super.(bool))
	cur_user_menus := c.GetSession("cur_user_menus")

	page := tools.CreatePaging(1, len(data_list), len(data_list))
	c.Data["page"] = page
	c.Data["key"] = key
	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["data_list"] = data_list
	c.Data["label"] = "任务日志"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "log/taskjs.html"
	c.TplName = "log/task.html"
}

func (c *LogController) TaskLogRet() {
	id, _ := c.GetInt("id", 0)
	task := models.GetTaskId(id)
	Ret := task.TaskRet
	m := map[string]interface{}{}
	js := []byte(Ret)
	err := json.Unmarshal(js, &m)
	if err != nil {
		c.Data["json"] = Ret
	} else {
		c.Data["json"] =m["ret"].(string)
	}
	c.ServeJSON()
}
